package main

import (
	"fmt"
	"os"
	"time"
	"golang.org/x/net/context"
	"google.golang.org/grpc"

	_ "./config" // 加载配置文件
	pb "./protobuf"
	grpclb "./etcdv3"
)

func main() {
	// etcd host target
	target := os.Getenv("EtcdHost")
	// balancer name
	serviceNamePrefix := os.Getenv("ServerNamePrefix")
	serviceName := os.Getenv("ServerName")
	fmt.Println(serviceNamePrefix, serviceName)
	// resolver
	resolver := grpclb.NewResolver(serviceNamePrefix, serviceName)
	// connect
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	conn, err := grpc.DialContext(ctx, target, grpc.WithInsecure(), grpc.WithBalancer(grpc.RoundRobin(resolver)))
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// client
	client := pb.NewKgTestClient(conn)
	// testHandler
	var testHandler KgTestClient

	//testHandler.SayHello(client)
	testHandler.SayHello2(client)
}

type KgTestClient struct{}

func (s *KgTestClient) SayHello2(client pb.KgTestClient) {
	ticker := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-ticker.C:
			s.SayHello(client)
		}
	}
}

func (s *KgTestClient) SayHello(client pb.KgTestClient) {
	req := &pb.HelloRequest{Name: "HelloWorld"}
	result, err := client.SayHello(context.Background(), req)

	if err != nil {
		fmt.Println("SayHello fail : ", err)
		return
	}
	fmt.Printf("SayHello success : %#v \n", result)
}
